<template>
  <page-header-wrapper :title="false">
    <div>
      <a-row id="home_wrapper" type="flex">
        <a-col id="left_tree" flex="400px">
          <div>
            <a-tree
              checkable
              :show-line="true"
              :show-icon="false"
              :show-leaf-icon="false"
              :treeData="orgAllTreeData"
              :replaceFields="orgTreereplaceFields"
              @select="onSelectOrgTree"
            >
            </a-tree>
          </div>
        </a-col>
        <div style="width: 10px"></div>
        <a-col flex="auto">
          <div id="right-content-white">
            <a-card title="" :bordered="false">
              <div class="table-page-search-wrapper">
                <a-form layout="inline">
                  <a-row :gutter="48">
                    <a-col :md="8" :sm="24">
                      <a-form-item label="单位名称">
                        <a-input v-model="orgQueryParam.keyword" placeholder="" />
                      </a-form-item>
                    </a-col>

                    <a-col :md="8" :sm="24">
                      <span class="table-page-search-submitButtons">
                        <a-button type="primary" @click="() => initQuery()">查询</a-button>
                        <!-- <a-button style="margin-left: 8px" @click="() => queryOrgParam = {}">重置</a-button> -->
                      </span>
                    </a-col>
                  </a-row>
                </a-form>

                <div class="table-operator">
                  <a-button type="primary" icon="plus" @click="() => handleAddOrg()">添加</a-button>
                  <a-popconfirm
                    title="确认删除所选单位？"
                    ok-text="确认"
                    cancel-text="取消"
                    @confirm="() => delOrg(orgSelectedRowKeys.join(','))"
                  >
                    <a-button v-if="orgSelectedRowKeys.length > 0" type="danger" icon="delete">批量删除</a-button>
                  </a-popconfirm>
                </div>

                <template>
                  <a-table
                    size="small"
                    bordered
                    :columns="orgColumns"
                    :row-key="(record) => record.id"
                    :data-source="orgData"
                    :pagination="orgPagination"
                    :loading="loading"
                    @change="handleOrgTableChange"
                    :row-selection="{ selectedRowKeys: orgSelectedRowKeys, onChange: onOrgSelectChange }"
                  >
                    <span slot="orgAction" slot-scope="text, record">
                      <a @click="() => handleEditOrg(record.id)"> <a-icon type="edit" /> 编辑 </a>
                      <a-divider type="vertical" />
                      <a-popconfirm
                        title="确认删除该单位？"
                        ok-text="确认"
                        cancel-text="取消"
                        @confirm="() => delOrg(record.id)"
                      >
                        <a href="#"> <a-icon type="delete" /> 删除</a>
                      </a-popconfirm>
                    </span>
                  </a-table>
                </template>
              </div>
            </a-card>
          </div>
        </a-col>
      </a-row>
    </div>

    <a-modal
      :maskClosable="false"
      :title="orgOperType == 'add' ? '添加单位' : '编辑单位'"
      :width="640"
      :visible="!!orgOperType"
      :confirmLoading="loading"
      @ok="() => addOrEditOrg()"
      @cancel="() => cancelAddOrEditOrg()"
      :forceRender="true"
    >
      <a-spin :spinning="loading">
        <a-form ref="orgOperForm" :form="form" v-bind="formLayout">
          <a-form-item v-show="false" label="主键ID">
            <a-input
              type="hidden"
              v-decorator="[
                'id',
                {
                  rules: [{ required: false }],
                },
              ]"
            />
          </a-form-item>
          <a-form-item v-show="orgOperType == 'add'" label="上级单位" required name="orgId">
            <a-tree-select
              v-decorator="[
                'orgId',
                {
                  rules: [{ required: true, message: '请选择上级单位', validateTrigger: 'blur' }],
                },
              ]"
              :filterTreeNode="onOrgOperFilter"
              show-search
              :replaceFields="orgTreereplaceFields"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="orgAllTreeData"
              placeholder="请选择"
              tree-default-expand-all
              allow-clear
            >
            </a-tree-select>
          </a-form-item>
          <a-form-item label="单位名称" required name="name">
            <a-input
              v-decorator="[
                'name',
                {
                  rules: [
                    { required: true, message: '请输入单位名称', whitespace: true, validateTrigger: 'blur' },
                    { max: 100, message: '单位名称长度不能超过100', trigger: 'blur' },
                  ],
                },
              ]"
            />
          </a-form-item>
          <a-form-item label="单位简称" required name="shortName">
            <a-input
              v-decorator="[
                'shortName',
                {
                  rules: [
                    { required: true, message: '请输入单位简称', whitespace: true, validateTrigger: 'blur' },
                    { max: 100, message: '单位简称长度不能超过100', trigger: 'blur' },
                  ],
                },
              ]"
            />
          </a-form-item>
          <a-form-item v-show="orgOperType == 'add'" label="单位类型" required name="type">
            <a-radio-group
              v-decorator="[
                'type',
                { rules: [{ required: true, message: '请选择单位类型', whitespace: true, validateTrigger: 'blur' }] },
              ]"
            >
              <a-radio value="OEM"> OEM商 </a-radio>
              <a-radio value="PROXY"> 代理商 </a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="单位地址" name="address">
            <a-input
              v-decorator="[
                'address',
                {
                  rules: [{ required: false }, { max: 100, message: '单位地址长度不能超过100', trigger: 'blur' }],
                },
              ]"
            />
          </a-form-item>
          <a-form-item label="注册日期" name="regdate">
            <a-date-picker
              v-decorator="['regdate', { rules: [{ required: false }] }]"
              type="date"
              placeholder="请选择"
              style="width: 100%"
              :disabled-date="disabledDate"
            />
          </a-form-item>
          <a-form-item label="城市区域" name="regionCode">
            <a-cascader
              v-decorator="['regionCode', { rules: [{ required: false }] }]"
              change-on-select
              :fieldNames="regionTreeReplaceFields"
              :options="regionTreeData"
              placeholder="请选择"
              :showSearch="true"
            />
          </a-form-item>
          <a-form-item
            v-show="orgOperType == 'add'"
            :required="orgOperType == 'add'"
            label="管理员姓名"
            name="adminName"
          >
            <a-input
              v-decorator="[
                'adminName',
                {
                  rules: [
                    { required: true, message: '请输入管理员姓名', whitespace: true, validateTrigger: 'blur' },
                    { max: 100, message: '管理员姓名长度不能超过100', trigger: 'blur' },
                  ],
                },
              ]"
            />
          </a-form-item>
          <a-form-item
            v-show="orgOperType == 'add'"
            :required="orgOperType == 'add'"
            label="管理员手机号"
            name="adminPhone"
          >
            <a-input
              v-decorator="[
                'adminPhone',
                {
                  rules: [
                    { required: true, message: '请输入管理员手机号', whitespace: true, validateTrigger: 'blur' },
                    { max: 11, message: '管理员手机号长度不能超过11', trigger: 'blur' },
                  ],
                },
              ]"
            />
          </a-form-item>
          <a-form-item
            v-show="orgOperType == 'add'"
            :required="orgOperType == 'add'"
            label="管理员密码"
            name="adminPwd"
          >
            <a-input
              v-decorator="[
                'adminPwd',
                {
                  rules: [
                    { required: true, message: '请输入管理员密码', whitespace: true, validateTrigger: 'blur' },
                    { max: 100, message: '管理员密码长度不能超过100', trigger: 'blur' },
                  ],
                },
              ]"
            />
          </a-form-item>
        </a-form>
      </a-spin>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import { TreeSelect, Cascader } from 'ant-design-vue'
import moment from 'moment'

const orgColumns = [
  {
    title: '单位名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '单位简称',
    dataIndex: 'shortName',
    key: 'shortName',
  },
  {
    title: '单位地址',
    dataIndex: 'address',
    key: 'address',
  },
  {
    title: '注册时间',
    key: 'regdate',
    dataIndex: 'regdate',
  },
  {
    title: '操作',
    key: 'OrgAction',
    scopedSlots: { customRender: 'orgAction' },
  },
]

export default {
  name: 'OrgList',
  components: {
    [Cascader.name]: Cascader,
    [TreeSelect.name]: TreeSelect,
    ATreeSelectNode: TreeSelect.TreeNode,
  },
  data() {
    return {
      loading: false,
      orgTreeSelect: '',
      orgOperType: '',
      orgOperTreeData: [],
      orgAllTreeData: [],
      orgAllData: [],
      orgTreereplaceFields: {
        title: 'lable',
        key: 'id',
        value: 'id',
      },
      regionTreeData: [],
      regionTreeReplaceFields: {
        value: 'id',
        label: 'lable',
        children: 'children',
      },
      formLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 20 },
      },
      orgColumns,
      orgSelectedRowKeys: [],
      orgQueryParam: {},
      orgPagination: {
        pageSize: 10,
        showQuickJumper: true,
        showTotal: (total, range) => `共 ${total} 条`,
      },
      orgData: [],
      form: this.$form.createForm(this),
    }
  },
  mounted() {
    this.getOrgTree()
    this.getRegionTree()
    this.queryOrgParam()
  },
  methods: {
    disabledDate(current) {
      return current > moment().endOf('day')
    },
    onOrgOperFilter(searchVal, treeNode) {
      return treeNode.data.props.lable.includes(searchVal)
    },
    onSelectOrgTree(selectedKeys, info) {
      this.orgTreeSelect = selectedKeys && selectedKeys.length > 0 ? selectedKeys[0] : ''
      this.orgPagination.current = 1
      this.queryOrgParam()
    },
    getOrgTree() {
      this.$http.get('/web/common/getOrgTree').then((res) => {
        if (res.code == 0) {
          this.orgAllTreeData = res.data
        }
      })
    },
    onOrgSelectChange(selectedRowKeys) {
      this.orgSelectedRowKeys = selectedRowKeys
    },
    getRegionTree() {
      this.$http.get('/web/dict/getRegionTree').then((res) => {
        if (res.code == 0) {
          this.regionTreeData = res.data
        }
      })
    },
    handleOrgTableChange(pagination, filters, sorter) {
      this.orgPagination.current = pagination.current
      this.orgPagination.pageSize = pagination.pageSize
      this.queryOrgParam(pagination.current, pagination.pageSize)
    },
    cancelAddOrEditOrg() {
      this.orgOperType = ''
    },
    handleEditOrg(id) {
      this.orgOperType = 'edit'
      const operData = this.orgData.filter((i) => i.id == id)[0]
      let tmp = {
        id: operData.id,
        name: operData.name,
        shortName: operData.shortName,
        address: operData.address,
        type: operData.type,
      }
      let regionCode = []
      if (operData.province) regionCode.push(operData.province)
      if (operData.city) regionCode.push(operData.city)
      if (operData.district) regionCode.push(operData.district)
      tmp.regionCode = regionCode

      if (operData.regdate) tmp.regdate = moment(operData.regdate)
      this.form.setFieldsValue(tmp)
    },
    handleAddOrg() {
      let preIsAdd = this.orgOperType == 'add'
      this.orgOperType = 'add'
      if (!preIsAdd) {
        // let tmp = {
        //   id: '',
        //   name: '',
        //   address: '',
        //   shortName: '',
        //   type: 'OEM',
        //   orgId: '',
        //   regdate: null,
        //   adminName: '',
        //   adminPhone: '',
        //   adminPwd: '',
        // }
        this.form.resetFields()
      }
    },
    addOrEditOrg() {
      const validateFieldsKey = ['name', 'shortName', 'type', 'address', 'regionCode', 'id','regdate']
      if (this.orgOperType === 'add') {
        validateFieldsKey.push(...['adminName', 'adminPhone', 'adminPwd', 'orgId'])
      }

      this.form.validateFields(validateFieldsKey, (error, values) => {
        if (error) return

        let param = values
        if (param.regdate) param.regdate = param.regdate.format('YYYY-MM-DD')
        //  处理行政区划
        if (param.regionCode && param.regionCode.length > 0) {
          if (param.regionCode[0]) param.province = param.regionCode[0]
          if (param.regionCode[1]) param.city = param.regionCode[1]
          if (param.regionCode[2]) param.district = param.regionCode[2]
        }
        this.loading = true
        this.$http.post(this.orgOperType == 'add' ? '/web/org/add' : '/web/org/update', param).then((res) => {
          this.loading = false
          if (res.code == 0) {
            this.$notification['success']({
              message: '成功',
              description: `单位${this.orgOperType == 'add' ? '添加' : '编辑'}成功`,
            })
            this.orgOperType = ''
            this.getOrgTree()
            this.queryOrgParam()
          } else {
            this.$notification['error']({
              message: '错误',
              description: res.message,
              duration: 4,
            })
          }
        })
      })
    },
    delOrg(id) {
      this.loading = true
      let param = { orgIds: id }
      this.$http.delete('/web/org/delete', { params: param }).then((res) => {
        this.loading = false
        if (res.code == 0) {
          this.$notification['success']({
            message: '成功',
            description: '单位已删除',
          })
          this.orgPagination.current = 1
          this.queryOrgParam()
        } else {
          this.$notification['error']({
            message: '错误',
            description: res.message,
            duration: 4,
          })
        }
      })
    },
    queryOrgParam() {
      this.loading = true
      let param = Object.assign({}, this.orgQueryParam)
      param.pOrgId = this.orgTreeSelect
      param.start = this.orgPagination.current
      param.limit = this.orgPagination.size
      this.$http.get('/web/org/page', { params: param }).then((res) => {
        this.loading = false
        if (res.code == 0) {
          let data = res.data
          this.orgData = data.records
          const pagination = { ...this.pagination }
          // Read total count from server
          // pagination.total = data.totalCount;
          pagination.total = data.total
          pagination.current = data.current
          pagination.pageSize = data.size
          this.orgPagination = pagination
        }
      })
    },
    initQuery() {
      this.orgPagination.current = 1
      this.queryOrgParam()
    },
  },
}
</script>